Private Const INFINITE = &HFFFFFFFF

' 定义标志变量
Dim thread1Completed As Boolean
Dim thread2Completed As Boolean

Sub Main() ' 主线程
    Dim ws As Worksheet
    On Error Resume Next ' 如果Sheet1不存在则忽略错误，但最好确保它存在
    Set ws = ThisWorkbook.Sheets("Sheet1")
    On Error GoTo 0 ' 恢复正常的错误处理
    If ws Is Nothing Then
        MsgBox "错误：找不到名为 'Sheet1' 的工作表。", vbCritical
        Exit Sub
    End If

    ' 清除旧状态并标记主线程开始
    ws.Range("A1:C1").ClearContents
    ws.Range("A1").Value = "主线程: 运行中..."

    ' 初始化标志变量
    thread1Completed = False
    thread2Completed = False

    ' 启动次线程模拟
    Application.OnTime Now + TimeValue("00:00:01"), "secondary1"
    Application.OnTime Now + TimeValue("00:00:01"), "secondary2"

    ' 等待所有次线程完成
    Do While Not (thread1Completed And thread2Completed)
        DoEvents ' 允许处理其他事件，例如OnTime事件
    Loop

    ' 所有次线程完成后执行的操作
    ws.Range("A1").Value = "主线程: 已完成"
    MsgBox "所有次线程已完成"
End Sub ' 主线程结束

Sub secondary1() ' 模拟次线程1
    Dim ws As Worksheet
    On Error Resume Next
    Set ws = ThisWorkbook.Sheets("Sheet1")
    On Error GoTo 0
    If ws Is Nothing Then Exit Sub ' 如果找不到工作表则退出

    ws.Range("B1").Value = "次线程1: 运行中..."

    ' 模拟耗时操作
    Application.Wait Now + TimeValue("00:00:05")

    ' 标记次线程1完成
    thread1Completed = True
    ws.Range("B1").Value = "次线程1: 已完成"
End Sub ' 模拟次线程1结束

Sub secondary2() ' 模拟次线程2
    Dim ws As Worksheet
    On Error Resume Next
    Set ws = ThisWorkbook.Sheets("Sheet1")
    On Error GoTo 0
    If ws Is Nothing Then Exit Sub ' 如果找不到工作表则退出

    ws.Range("C1").Value = "次线程2: 运行中..."

    ' 模拟耗时操作
    Application.Wait Now + TimeValue("00:00:05")

    ' 标记次线程2完成
    thread2Completed = True
    ws.Range("C1").Value = "次线程2: 已完成"
End Sub ' 模拟次线程2结束
